<template>
    <div>
        <el-card>
            <div slot="header" class="clearfix">
                <i class="el-icon-s-cooperation"></i>
                考试助手
            </div>
            <div>
                <p style="font-size: 12px;color: darkgray;">
                    剩余时间：
                </p>
                <div id="djs">
                    <i class="el-icon-timer" style="color: #00a1ff;"></i>
                    <span v-if="d!=0||d!='0'||d!='00'" style="font-size: 12px;font-weight: bold;">
                        {{d}}天
                    </span>
                    {{djs}}
                </div>

                <div id="dtk">
                    <el-row>
                        <el-col :span="2" v-for="i in len" :key="i">
                            <div class="every-item-tip"
                                 :class="{'done':showDone(i)}"
                                 @click="changeTo(i)">
                                {{i}}
                            </div>
                        </el-col>
                    </el-row>
                </div>
                <div class="tool">
                    <div
                            class="tool-item"
                            style="background-color:#ff5a00;">
                        <div>
                            {{goOutCount}}
                        </div>
                        <p>离场</p>
                    </div>
                    <div
                            @click="handUp()"
                            class="tool-item" style="background-color:#ffc200;">
                        <div>
                            <i class="el-icon-c-scale-to-original"></i>
                        </div>
                        <p>模式</p>
                    </div>
                    <div
                            @click="moniVisible=canUserMedia?!moniVisible:moniVisible"
                            class="tool-item"
                            style="background-color:#0083ff;">
                        <div>
                            <i class="el-icon-video-camera"></i>
                        </div>
                        <p>监控</p>
                    </div>
                    <div
                            @click="myInfo()"
                            class="tool-item" style="background-color:#00e739;">
                        <div>
                            <i class="el-icon-s-claim"></i>
                        </div>
                        <p>准考证</p>
                    </div>
                    <div
                            @click="close()"
                            class="tool-item" style="background-color:#ff2800;">
                        <div>
                            <i class="el-icon-circle-close"></i>
                        </div>
                        <p>退出</p>
                    </div>
                </div>
                <div>
                    <el-button
                            @click="submit"
                            style="width: 100%"
                            icon="el-icon-document-checked"
                            type="primary">立即交卷
                    </el-button>
                </div>
            </div>
        </el-card>

        <el-dialog
                top="0"
                :visible.sync="dialogVisible"
                width="80%">
            <admissionTicket :examId="info.id"/>
            <span slot="footer" class="dialog-footer">
  </span>
        </el-dialog>

        <div id="moni" :style="{'left':moniVisible?'0px':'-175px'}">
            <div id="ssjk" v-if="canUserMedia">
                <div class="ssjk-text">
                </div>
                <video ref="video" width="175" height="100" autoplay="autoplay"></video>
            </div>
        </div>
    </div>
</template>

<script>
    import admissionTicket from "../myExam/admissionTicket";
    import {exameeOnliner, querySelfExamRegistration} from "../../../api/examination";

    export default {
        name: "index",
        props: ["examInfo", "err", "len"],
        components: {admissionTicket},
        data() {
            return {
                djs: "00" + " : " + "00" + " : " + "00",//倒计时
                d: 0,//天数
                info: {},//考试信息
                exammerInfo: {},
                timer: null,//倒计时
                moniVisible: false,
                dialogVisible: false,
                submitFlag: false,//提交信号标志
                mediaStreamTrack: null,
                goOutCount: 0,
                canUserMedia: false,
            }
        },
        mounted() {
            this.goOutCount = sessionStorage.getItem("goOutCount") || 0;
            this.$store.commit("clearAnsweredIds")
            this.$store.commit("setAnswerMode", 1)
        },
        beforeDestroy() {
            this.clearInterval()
            this.closeScreenWatch();
            this.removeChangeTabListener();
            sessionStorage.setItem("goOutCount", this.goOutCount);
        },
        methods: {
            userMediaInit() {
                if (navigator.mediaDevices && config.useExamMedia) {
                    this.canUserMedia = true;
                    this.getMedia()
                }
            },
            closeScreenWatch() {
                this.mediaStreamTrack && this.mediaStreamTrack.stop();
            },
            submit() {
                if (this.submitFlag) {
                    this.$message.warning("请勿重复提交试卷！")
                    return false;
                }
                let msg = "确定交卷？";

                let arr = JSON.parse(this.$store.state.answeredIds)
                let len = arr == null ? 0 : arr.length;
                let notdo = this.len - len
                if (notdo > 0) {
                    msg = msg + `你还有 ${notdo} 道试题未完成！`
                }
                this.$confirm(msg, '提示', {type: "warning"}).then(() => {
                    this.$emit("submit")
                    this.clearInterval()
                    this.submitFlag = true
                    this.closeScreenWatch();
                    sessionStorage.removeItem("goOutCount");
                }).catch(err => {
                })
            },
            handUp() {
                if (this.$store.state.answerMode === 1) {
                    this.$store.commit("setAnswerMode", 2)
                } else {
                    this.$store.commit("setAnswerMode", 1)
                }
            },
            close() {
                this.$confirm('即将退出考试, 是否继续?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$router.replace("/ei/myExam")
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '继续考试'
                    });
                });
            },
            myInfo() {
                this.dialogVisible = true
                this.$emit("myInfo")
            },
            clearInterval() {
                clearInterval(this.timer)
            },
            insertO(num) {
                if (num < 10) {
                    return "0" + num
                }
                return num;
            },
            djsHandler() {
                const overTime = (new Date(this.info.examOverTime)).getTime()
                let now = new Date().getTime()
                if (now >= overTime) {
                    this.gameOver();
                    this.djs = "00" + " : " + "00" + " : " + "00";
                    clearInterval(this.timer)
                    return false;
                }
                let EndTime = new Date(overTime);
                let NowTime = new Date();
                let t = EndTime.getTime() - NowTime.getTime();

                let d = Math.floor(t / 1000 / 60 / 60 / 24)
                let h = this.insertO(Math.floor(t / 1000 / 60 / 60 % 24))
                let i = this.insertO(Math.floor(t / 1000 / 60 % 60))
                let s = this.insertO(Math.floor(t / 1000 % 60))
                this.d = d
                this.djs = h + " : " + i + " : " + s;

                //发送心跳
                this.online();
            },

            beginDjs() {
                //开始倒计时 发送心跳
                this.djsHandler();
                //初始化摄像头
                this.userMediaInit()
                //离开页面监听
                this.changeTabListener();

                this.timer = setInterval(this.djsHandler, 1000)
            },
            async online() {
                let data = {
                    examId: this.exammerInfo.examId,
                    examCardNum: this.exammerInfo.examCardNum,
                    username: this.exammerInfo.username,
                    photo: this.takePhoto()
                }
                await exameeOnliner(data)
            },
            gameOver() {
                if (this.submitFlag) {
                    return false;
                }
                this.$message.warning("考试时间到，自动交卷！")
                this.submitFlag = true;
                this.$emit("submit")
                this.clearInterval()
                this.closeScreenWatch();
                this.removeChangeTabListener();
            },
            getMedia() {
                console.log("getMedia")
                let constraints = {
                    video: {width: 1280, height: 720},
                    audio: false
                }
                let promise = navigator.mediaDevices.getUserMedia(constraints);
                promise.then(MediaStream => {
                    this.$refs.video.srcObject = MediaStream
                    this.$refs.video.play()
                    this.mediaStreamTrack = typeof MediaStream.stop === 'function' ? MediaStream : MediaStream.getTracks()[0]
                    if (!this.mediaStreamTrack) {
                        console.log("无法调用摄像头");
                        this.canUserMedia = false;
                    }
                }).catch(function (PermissionDeniedError) {
                    console.log(PermissionDeniedError);
                })
            },
            takePhoto() {
                if (!this.canUserMedia) {
                    return null;
                }
                let video = this.$refs.video;
                const canvas = document.createElement("canvas")
                const width = 1280
                const height = 720
                canvas.width = width;
                canvas.height = height;
                try {
                    canvas.getContext('2d').drawImage(video, 0, 0, width, height); //将图片绘制到canvas中
                } catch (e) {

                }
                return canvas.toDataURL('image/jpeg')
            },
            changeTabHandle() {
                if (document.visibilityState === 'hidden') {
                    document.title = '离开考试页面警告';
                    this.goOutCount++
                    sessionStorage.setItem("goOutCount", this.goOutCount);
                } else {
                    document.title = "在线考试";
                }
            },
            changeTabListener() {
                document.addEventListener('visibilitychange', this.changeTabHandle);
            },
            removeChangeTabListener() {
                document.removeEventListener('visibilitychange', this.changeTabHandle);
            },
            //切换题目
            changeTo(i) {
                let answerMode = this.$store.state.answerMode
                this.$emit("changeCurrent", {id: i})
                if (answerMode === 1) {
                    document.getElementById("timu" + i).scrollIntoView({behavior: "smooth"});
                    return false
                }
                if (answerMode === 2) {
                }
                this.$emit("changeCurrent", {id: i})
            },
            showDone(i) {
                let arr = JSON.parse(this.$store.state.answeredIds)
                if (arr != null) {
                    return arr.includes(i)
                }
                return false;
            }
        },
        watch: {
            examInfo(newVal, oldVal) {
                this.info = newVal
                const overTime = (new Date(this.info.examOverTime)).getTime()
                if (overTime < new Date().getTime()) {
                    this.submitFlag = true
                    return false
                }
                querySelfExamRegistration(this.info.id).then(resp => {
                    this.exammerInfo = resp.data
                }).catch(err => {
                }).finally(() => {
                    this.beginDjs();
                })

            },
        },
    }
</script>

<style scoped lang="scss">
    #djs {
        text-align: center;
        font-size: 32px;
        margin: 5px auto;
    }

    .tool {
        margin: 5px auto;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .tool-item {
            color: #f5f5f5;
            padding-top: 10px;
            cursor: pointer;
            width: 50px;
            height: 50px;
            margin: 10px;
            text-align: center;
            border-radius: 10%;
            box-shadow: 2px 2px 5px #c3c3c3;

            p {
                margin: 0;
                font-size: 12px;
                font-weight: bold;
            }
        }
    }

    #moni {
        transition: 1s;
        position: fixed;
        bottom: 0;
        left: 0;
        background-color: #cecece;
        z-index: 500;

        #ssjk {
            margin: 0;
            height: 100px;
            position: relative;
            padding: 0;

            canvas {
                width: 100%;
            }

            .ssjk-text {
                position: absolute;
                top: 0;
                left: 0;
                font-size: 12px;
                color: #f3f3f3;
            }
        }

    }

    #dtk {
        padding: 5px;
        margin: 15px auto;
        max-height: 316px;
        overflow: auto;

        .every-item-tip {
            border: 1px solid #dadada;
            width: 30px;
            height: 30px;
            margin: 2px auto;
            font-size: 12px;
            color: #787b80;
            text-align: center;
            line-height: 30px;
            cursor: pointer;
            overflow: hidden;

            &:hover {
                color: #ff5a00;
            }
        }

        .done {
            color: #f3f3f3;
            background-color: #0083ff;
        }

        .current {
            color: #f3f3f3;
            background-color: #ff2800;
        }
    }

</style>